<template>
  <view class="form-container">
    <uni-forms ref="form" :model="formData" :rules="rules" :show-message="false">
      <view class="form-card">
        <view class="card-title">
          <uni-icons type="person" size="18" color="#409eff"></uni-icons>
          <text>基本信息</text>
        </view>

        <view class="form-group">
          <view class="form-label required">用户昵称</view>
          <uni-forms-item name="nickName">
            <uni-easyinput v-model="formData.nickName" placeholder="请输入用户昵称" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label required">用户名称</view>
          <uni-forms-item name="userName">
            <uni-easyinput v-model="formData.userName" placeholder="请输入用户名称" :disabled="!!formData.userId" />
          </uni-forms-item>
        </view>

        <view class="form-group" v-if="!formData.userId">
          <view class="form-label required">密码</view>
          <uni-forms-item name="password">
            <uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">手机号码</view>
          <uni-forms-item name="phonenumber">
            <uni-easyinput v-model="formData.phonenumber" placeholder="请输入手机号码" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">邮箱</view>
          <uni-forms-item name="email">
            <uni-easyinput v-model="formData.email" placeholder="请输入邮箱" />
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">用户性别</view>
          <uni-forms-item name="sex">
            <picker @change="handleSexChange" :value="sexIndex" :range="sexOptions" range-key="text">
              <view class="picker-box">
                <text>{{ sexOptions[sexIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>

        <view class="form-group">
          <view class="form-label">状态</view>
          <uni-forms-item name="status">
            <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="text">
              <view class="picker-box">
                <text>{{ statusOptions[statusIndex].text }}</text>
                <uni-icons type="bottom" size="14" color="#999"></uni-icons>
              </view>
            </picker>
          </uni-forms-item>
        </view>
      </view>

      <!-- 角色信息 -->
      <view class="form-card">
        <view class="card-title">
          <uni-icons type="staff" size="18" color="#409eff"></uni-icons>
          <text>角色信息</text>
        </view>
        <view class="form-group">
          <uni-forms-item name="roleIds">
            <uni-data-checkbox v-model="formData.roleIds" multiple :localdata="roleOptions" mode="tag" />
          </uni-forms-item>
        </view>
      </view>

      <!-- 岗位信息 -->
      <view class="form-card">
        <view class="card-title">
          <uni-icons type="flag" size="18" color="#409eff"></uni-icons>
          <text>岗位信息</text>
        </view>
        <view class="form-group">
          <uni-forms-item name="postIds">
            <uni-data-checkbox v-model="formData.postIds" multiple :localdata="postOptions" mode="tag" />
          </uni-forms-item>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="form-actions">
        <button class="submit-btn" type="primary" @click="submitForm">确 定</button>
        <button class="cancel-btn" @click="cancel">取 消</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { addUser, updateUser, getUser } from '@/api/system/user'

export default {
  data() {
    return {
      formData: {
        userId: undefined,
        nickName: '',
        userName: '',
        password: '',
        phonenumber: '',
        email: '',
        sex: '0',
        status: '0',
        roleIds: [],
        postIds: []
      },
      rules: {
        nickName: {
          rules: [{ required: true, errorMessage: '请输入用户昵称' }]
        },
        userName: {
          rules: [{ required: true, errorMessage: '请输入用户名称' }]
        },
        password: {
          rules: [{ required: true, errorMessage: '请输入密码' }]
        },
        email: {
          rules: [{
            required: false,
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            errorMessage: '邮箱格式不正确'
          }]
        },
        phonenumber: {
          rules: [{
            required: false,
            pattern: /^1[3-9]\d{9}$/,
            errorMessage: '手机号格式不正确'
          }]
        }
      },
      sexOptions: [
        { text: '男', value: '0' },
        { text: '女', value: '1' },
        { text: '未知', value: '2' }
      ],
      statusOptions: [
        { text: '正常', value: '0' },
        { text: '停用', value: '1' }
      ],
      roleOptions: [], // 角色选项
      postOptions: [], // 岗位选项
      title: '',
      inputStyles: {
        color: '#2c3e50',
        borderColor: '#dcdfe6'
      },
      sexIndex: 0,
      statusIndex: 0
    }
  },
  onLoad(options) {
    if (options.userId) {
      this.title = '修改用户'
      this.formData.userId = options.userId.toString()
      this.getDetail()
    } else {
      this.title = '新增用户'
    }
    uni.setNavigationBarTitle({
      title: this.title
    })
  },
  methods: {
    // 获取用户详情
    async getDetail() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })

        const res = await getUser(this.formData.userId)

        uni.hideLoading()

        if (res.code === 200) {
          const { user, roles, posts, roleIds, postIds } = res.data

          // 设置表单数据
          Object.assign(this.formData, user)

          // 设置已选中的角色和岗位
          this.formData.roleIds = roleIds || []
          this.formData.postIds = postIds || []

          // 设置性别和状态的选中索引
          this.sexIndex = this.sexOptions.findIndex(item => item.value === user.sex)
          this.statusIndex = this.statusOptions.findIndex(item => item.value === user.status)

          // 设置角色选项
          this.roleOptions = roles.map(item => ({
            text: item.roleName,
            value: item.roleId
          }))

          // 设置岗位选项
          this.postOptions = posts.map(item => ({
            text: item.postName,
            value: item.postId
          }))
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        uni.hideLoading()
        const errorMsg = error.response?.data?.msg || '服务器异常，请稍后重试'
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate().then(async () => {
        try {
          uni.showLoading({
            title: '保存中...',
            mask: true
          })

          const submitMethod = this.formData.userId ? updateUser : addUser
          const result = await submitMethod(this.formData)

          if (result.code === 200) {
            // 返回上一页并刷新列表
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]

            // 通知上一页刷新数据
            if (prevPage && prevPage.$vm) {
              prevPage.$vm.handleQuery()
            }

            uni.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 1000
            })

            // 缩短返回延时
            setTimeout(() => {
              uni.navigateBack()
            }, 1000)
          }
        } catch (error) {
          uni.hideLoading()
        }
      }).catch(errors => {
        const firstError = Object.values(errors)[0]?.errorMessage
        if (firstError) {
          uni.showToast({
            title: firstError,
            icon: 'none',
            duration: 2000
          })
        }
      })
    },

    // 取消
    cancel() {
      uni.navigateBack()
    },

    // 性别选择改变
    handleSexChange(e) {
      this.sexIndex = e.detail.value
      this.formData.sex = this.sexOptions[this.sexIndex].value
    },

    // 状态选择改变
    handleStatusChange(e) {
      this.statusIndex = e.detail.value
      this.formData.status = this.statusOptions[this.statusIndex].value
    }
  }
}
</script>

<style lang="scss">
.form-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;

  .form-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

    .card-title {
      display: flex;
      align-items: center;
      margin-bottom: 36rpx;
      padding-bottom: 24rpx;
      border-bottom: 2rpx solid #f0f0f0;

      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #2c3e50;
        margin-left: 16rpx;
      }
    }

    .form-group {
      margin-bottom: 32rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label {
        font-size: 28rpx;
        color: #606266;
        margin-bottom: 16rpx;
        font-weight: 500;

        &.required::before {
          content: '*';
          color: #f56c6c;
          margin-right: 8rpx;
        }
      }

      :deep(.uni-forms-item) {
        margin: 0;
        padding: 0;

        // 隐藏表单项自带的错误提示
        .uni-forms-item__error {
          display: none;
        }

        .uni-forms-item__content {
          .uni-easyinput__content {
            background-color: #f8f9fa;
            border-radius: 12rpx;
            height: 88rpx;
            padding: 0 28rpx;

            &.is-input-error {
              background-color: #fff5f5;
              border: 1px solid #f56c6c;
            }

            input {
              font-size: 28rpx;
              color: #2c3e50;

              &::placeholder {
                color: #909399;
              }
            }
          }

          .uni-data-checklist {
            background-color: transparent;
            padding: 0;

            .uni-data-checklist-item {
              margin-right: 32rpx;
              padding: 16rpx 0;

              // 单选框样式
              .uni-radio-input {
                width: 36rpx;
                height: 36rpx;
                border-color: #dcdfe6;

                &.uni-radio-input-checked {
                  background-color: #409eff !important;
                  border-color: #409eff !important;
                }
              }

              // 多选框样式
              &.checklist-box {
                background-color: #f0f7ff;
                border-radius: 8rpx;
                padding: 12rpx 24rpx;
                margin-bottom: 16rpx;
                border: 2rpx solid #e1efff;

                &.is-checked {
                  background-color: #409eff;
                  border-color: #409eff;

                  .checklist-text {
                    color: #fff;
                  }
                }
              }

              .checklist-text {
                font-size: 28rpx;
                color: #606266;
              }
            }
          }
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 32rpx;
    margin-top: 48rpx;
    padding: 0 30rpx;
    margin-bottom: 48rpx;

    button {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      font-size: 30rpx;
      font-weight: 500;
      border-radius: 44rpx;
      transition: all 0.3s;

      &:active {
        transform: scale(0.98);
        opacity: 0.9;
      }

      &.submit-btn {
        background-color: #409eff;
        color: #fff;
        box-shadow: 0 8rpx 16rpx rgba(64,158,255,0.2);
      }

      &.cancel-btn {
        background-color: #f5f7fa;
        color: #606266;
        border: 2rpx solid #dcdfe6;
      }
    }
  }
}

// 禁用状态样式
:deep(.is-disabled) {
  .uni-easyinput__content {
    background-color: #f5f7fa !important;

    input {
      color: #909399 !important;
    }
  }
}

.picker-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  height: 88rpx;
  padding: 0 28rpx;
  font-size: 28rpx;
  color: #2c3e50;

  .uni-icons {
    margin-left: 12rpx;
  }
}
</style>